#!/usr/bin/env python3
"""
环境准备与依赖安装脚本
用于设置手势识别项目的Python环境
"""

import subprocess
import sys
import os

def install_packages():
    """安装项目所需的Python包"""
    packages = [
        "ultralytics>=8.0.0",
        "tensorflow>=2.10.0", 
        "opencv-python>=4.6.0",
        "numpy>=1.21.0",
        "matplotlib>=3.5.0",
        "scikit-learn>=1.0.0",
        "Pillow>=9.0.0",
        "seaborn>=0.12.0",
        "pandas>=1.5.0",
        "tqdm>=4.64.0",
        "colorama>=0.4.6"
    ]
    
    print("正在安装项目依赖包...")
    
    for package in packages:
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", package])
            print(f"✓ 成功安装: {package}")
        except subprocess.CalledProcessError as e:
            print(f"✗ 安装失败: {package}")
            print(f"错误信息: {e}")
            return False
    
    return True

def check_installation():
    """检查关键包是否成功安装"""
    packages_to_check = [
        ("ultralytics", "YOLOv8手部检测"),
        ("tensorflow", "手势分类模型"),
        ("cv2", "OpenCV图像处理"),
        ("numpy", "数值计算"),
        ("matplotlib", "数据可视化"),
        ("sklearn", "机器学习工具"),
        ("PIL", "图像处理"),
        ("seaborn", "统计可视化"),
        ("pandas", "数据处理"),
        ("tqdm", "进度条显示"),
        ("colorama", "终端颜色输出")
    ]
    
    print("\n检查包安装状态...")
    
    for package_name, description in packages_to_check:
        try:
            if package_name == "cv2":
                import cv2
                print(f"✓ {description} (OpenCV) - 版本: {cv2.__version__}")
            elif package_name == "PIL":
                from PIL import Image
                print(f"✓ {description} (Pillow) - 版本: {Image.__version__}")
            elif package_name == "sklearn":
                import sklearn
                print(f"✓ {description} (scikit-learn) - 版本: {sklearn.__version__}")
            else:
                module = __import__(package_name)
                version = getattr(module, '__version__', '未知版本')
                print(f"✓ {description} ({package_name}) - 版本: {version}")
        except ImportError:
            print(f"✗ {description} ({package_name}) - 未安装")
            return False
    
    return True

def main():
    """主函数"""
    print("=" * 60)
    print("手势识别项目 - 环境设置脚本")
    print("=" * 60)
    
    # 安装包
    if not install_packages():
        print("\n部分包安装失败，请手动检查依赖关系")
        sys.exit(1)
    
    # 检查安装
    if not check_installation():
        print("\n环境设置不完整，请检查错误信息")
        sys.exit(1)
    
    print("\n" + "=" * 60)
    print("✓ 环境设置完成！")
    print("=" * 60)
    print("\n下一步：运行数据预处理脚本准备数据集")
    print("命令: python data_preprocessing.py")

if __name__ == "__main__":
    main()